package qq2564874169.tuaotuao.fx.encrypt;

import qq2564874169.tuaotuao.fx.utils.ExUtil;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Decrypt {
    public static String aes(String value, String key, String padding) {
        try {
            byte[] raw = key.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance(padding);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] data = Base64.getDecoder().decode(value);
            byte[] original = cipher.doFinal(data);
            return new String(original, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw ExUtil.toRuntime(e);
        }
    }

    public static String aes(String value, String key) {
        return aes(value, key, "AES/ECB/PKCS5Padding");
    }

    public static String des(String input, String key, String padding) {
        try {
            byte[] data = Base64.getDecoder().decode(input);
            DESKeySpec ks = new DESKeySpec(key.getBytes(StandardCharsets.UTF_8));
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
            SecretKey sk = skf.generateSecret(ks);
            Cipher cipher = Cipher.getInstance(padding);
            byte[] iv = key.getBytes(StandardCharsets.UTF_8);
            IvParameterSpec iv2 = new IvParameterSpec(iv);
            cipher.init(Cipher.DECRYPT_MODE, sk, iv2);
            byte[] decryptedData = cipher.doFinal(data);
            return new String(decryptedData, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw ExUtil.toRuntime(e);
        }
    }

    public static String des(String input, String key) {
        return des(input, key, "DES/CBC/PKCS5Padding");
    }
}
